package com.ly.base.socket;
import org.junit.jupiter.api.Test;

import	java.util.concurrent.CompletableFuture;
import	java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import	java.net.Socket;
import java.net.SocketAddress;
import java.nio.channels.AsynchronousSocketChannel;



/**
 * @Classname WebSocket
 * @Description TODO
 * @Date 2020/11/1 9:12
 * @Author 冷心影翼
 */

public class WebSocket {

	@Test
	public void client() throws IOException {
		Socket socket = new Socket("127.0.0.1",8848);
		OutputStream outputStream = socket.getOutputStream();
		outputStream.write("你好".getBytes());
		socket.shutdownOutput();

		ByteArrayOutputStream bao = new ByteArrayOutputStream();
		InputStream inputStream = socket.getInputStream();
		byte [] buffer = new byte [1024];
		int i;
		while ((i = inputStream.read(buffer)) != -1) {
			bao.write(buffer);
		}


		System.out.println(bao.toString());

		bao.close();
		inputStream.close();
		socket.close();
		outputStream.close();
	}

	@Test
	public void server() throws IOException {
		ServerSocket serverSocket = new ServerSocket(8848);
		Socket socket = serverSocket.accept();
		InputStream inputStream = socket.getInputStream();

		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int i;
		while ((i = inputStream.read(data)) != -1) {
			outputStream.write(data);
		}
		socket.shutdownInput();

		System.out.println(outputStream.toString());
		OutputStream os = socket.getOutputStream();
		os.write(new String("accept").getBytes());

		os.close();
		outputStream.close();
		socket.close();
		serverSocket.close();
	}

}
